package com.zhlwish.dbunitdemo.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zhlwish.dbunitdemo.entity.User;

public class UserDaoImpl extends BaseDao implements IUserDao {

	public Long save(User user) throws Exception {
		Long id = null;
		PreparedStatement stm = getConnection().prepareStatement(
				"insert into user(username, password, name) values(?, ?, ?)",
				Statement.RETURN_GENERATED_KEYS);
		stm.setString(1, user.getUsername());
		stm.setString(2, user.getPassword());
		stm.setString(3, user.getName());
		stm.executeUpdate();
		ResultSet rs = stm.getGeneratedKeys();
		if (rs.first()) {
			id = rs.getLong(1);
		}
		closeConnection();
		return id;
	}

	public User get(Long id) throws Exception {
		User user = null;
		PreparedStatement stm = getConnection().prepareStatement(
				"select username, password, name from user where id=?");
		stm.setLong(1, id);
		ResultSet rs = stm.executeQuery();
		if (rs.first()) {
			user = new User();
			user.setUsername(rs.getString(1));
			user.setPassword(rs.getString(2));
			user.setName(rs.getString(3));
			user.setId(id);
		}
		closeConnection();
		return user;
	}

	public void delete(Long id) throws Exception {
		PreparedStatement stm = getConnection().prepareStatement(
				"delete from user where id=?");
		stm.setLong(1, id);
		stm.executeUpdate();
		closeConnection();
	}

	public List<User> list() throws Exception {
		List<User> users = new ArrayList<User>();
		PreparedStatement stm = getConnection().prepareStatement(
				"select username, password, name, id from user");
		ResultSet rs = stm.executeQuery();
		while (rs.next()) {
			User user = new User();
			user.setUsername(rs.getString(1));
			user.setPassword(rs.getString(2));
			user.setName(rs.getString(3));
			user.setId(rs.getLong(4));
			users.add(user);
		}
		closeConnection();
		return users;
	}
}
